package org.graduation.rbac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.graduation.model.common.RBAC.*;
import org.graduation.model.common.ResponseResult;
import org.graduation.model.common.user.User;
import org.graduation.rbac.mapper.QueryWrapperFactory;
import org.graduation.rbac.mapper.RolePermissionMapper;
import org.graduation.rbac.mapper.UserAndNotePermissionsMapper;
import org.graduation.rbac.service.UserAndNotePermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserAndNotePermissionsServiceImpl extends ServiceImpl<UserAndNotePermissionsMapper, UserAndNotePermissions> implements UserAndNotePermissionsService {

    @Autowired
    private UserAndNotePermissionsMapper userAndNotePermissionsMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public ResponseResult assignRole(User user, RBACModelTag model, Roles role) {
        UserAndNotePermissions userAndNotePermissions = new UserAndNotePermissions();
        userAndNotePermissions.setUid(user.getUid());
        userAndNotePermissions.setNoteId(model.getLongId());
        userAndNotePermissions.setRoleId(role.getRoleId());
        userAndNotePermissionsMapper.insert(userAndNotePermissions);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult revokeRole(User user, RBACModelTag model, Roles role) {
        UserAndNotePermissions userAndNotePermissions = new UserAndNotePermissions();
        userAndNotePermissions.setUid(user.getUid());
        userAndNotePermissions.setNoteId(model.getLongId());
        userAndNotePermissions.setRoleId(role.getRoleId());
        userAndNotePermissionsMapper.deleteById(userAndNotePermissions);
        return ResponseResult.success();
    }

    @Override
    public Set<Permissions> getUserAllPermissions(User user, RBACModelTag model) {
        Set<Permissions> permissions = new HashSet<>();
        // 1.获取用户关于model的所有角色
        List<UserAndNotePermissions> userAndNotePermissions = userAndNotePermissionsMapper.selectList(QueryWrapperFactory.getUserAndNoteRole(model, user.getUid()));
        for (UserAndNotePermissions userAndNotePermission : userAndNotePermissions) {
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(QueryWrapperFactory.getRolePermissions(userAndNotePermission.getRoleId()));
            for (RolePermission rolePermission : rolePermissions) {
                permissions.add(Permissions.valueOf(rolePermission.getPermissionId()));
            }
        }
        // 2.根据角色找到对应的权限
        return permissions;
    }

    @Override
    public Boolean checkPermission(User user, RBACModelTag model, Permissions permissions) {
        return getUserAllPermissions(user, model).contains(permissions);
    }
}
